<template>
  <div class="home">
    <div class="movie-filters">
      <div class="movie-filter">地区：
        <span v-for="area in areas" :class="{ active: requestData.area === area }" @click="reload({area: area})">{{ area }}</span>
      </div>
      <div class="movie-filter">分类：
        <span :class="{ active: requestData.category_id === 0}">全部</span>
        <span v-for="category in categories" :class="{ active: requestData.category_id === category.id }" @click="reload({category_id: category.id})">{{ category.name }}</span>
      </div>
      <div class="movie-filter">年代：
        <span v-for="year in years" :class="{ active: requestData.year === year.value }" @click="reload({year: year.value})">{{ year.name }}</span></a>
      </div>
      <div class="movie-filter">排序：
        <span v-for="order in orders" :class="{ active: requestData.order === order.value }" @click="reload({order: order.value})">{{ order.name }}</span>
      </div>
    </div>

    <div class="card-expansion">
      <div class="movie-top-progress">
        <md-progress-bar md-mode="indeterminate" v-show="loading" />
      </div>
      <div class="movie-list">
        <md-card :key="index" :class="{ zoom: movie.zoom, 'movie-minbox': true }" v-for="(movie, index) in movies">
          <div class="box-left">
            <md-card-media>
              <img
                :src="'https://doubanqaq.oss-cn-shenzhen.aliyuncs.com/' + (movie.cover_image.path ? movie.cover_image.path : 'movie_default_large.png')"
                :alt="movie.name"
                @click="zoom(index)"
              >
            </md-card-media>
            <md-card-header>
              <div class="md-subhead">
                <router-link :to="'/movies/' + movie.id" :title="movie.name">{{ movie.name }}</router-link>
              </div>
            </md-card-header>
          </div>
          <md-list v-show="movie.zoom" style="flex: 2 1 auto;flex-flow: column;">
            <md-list-item>
              <md-icon style="margin-right: 5px;">calendar_today</md-icon>
              <span style="flex:1; text-align:center;" :class="{'md-caption': movie.isWatch === 'watching', 'md-subheading': !movie.isWatch}">{{ movie.current_user_watch_status }}</span>
            </md-list-item>
            <md-list-item>
              <md-icon style="margin-right: 5px;">assignment_turned_in</md-icon>
              <md-button class="md-primary" v-if="!movie.isWatch" @click="watch(movie.id)">
                开始打卡
              </md-button>
              <md-button class="md-primary" v-else-if="movie.isWatch === 'watching'" @click="watched(movie.id)">
                完成打卡
              </md-button>
            </md-list-item>
            <md-list-item>
              <md-icon style="margin-right: 5px;">view_list</md-icon>
              <md-button class="md-primary">加入看单</md-button>
            </md-list-item>
            <md-list-item>
              <md-icon style="margin-right: 5px;">view_list</md-icon>
              <md-button class="md-primary">查看详情</md-button>
            </md-list-item>
          </md-list>
        </md-card>
      </div>
    </div>
    <div class="loading">
      <md-snackbar class="md-accent" md-position="left" :md-duration="Infinity" :md-active.sync="loading">
        <span>正在加载。。。</span>
      </md-snackbar>
    </div>
    <md-snackbar class="md-accent" md-position="left" :md-duration="3000" :md-active.sync="showMessage">
      <span>{{ message }}</span>
    </md-snackbar>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "home",
  computed: {
    // 使用对象展开运算符，将 mapState 对象混入到计算属性之中
    ...mapState([
      // 映射 this.auth 为 store.state.auth
      "auth",
      // 映射 this.user 为 store.state.user
      "user"
    ]),

  },
  data: () => ({
    categories: [],
    areas: [],
    comments: [],
    movies: [],
    message: null,
    showMessage: false,
    orders: [
      {
        name: "评分从高到低",
        value: "score_desc"
      },
      {
        name: "评分从低到高",
        value: "score_asc"
      },
      {
        name: "年代从近到远",
        value: "year_desc"
      },
      {
        name: "年代从远到近",
        value: "year_asc"
      },
      {
        name: "热度从高到低",
        value: "hot_desc"
      },
      {
        name: "热度从低到高",
        value: "hot_asc"
      }
    ],
    years: [
      {
        name: "全部",
        value: 0
      },
      {
        name: 2019,
        value: 2019
      },
      {
        name: 2018,
        value: 2018
      },
      {
        name: "2010年代",
        value: "-2010"
      },
      {
        name: "2000年代",
        value: "-2000"
      },
      {
        name: "90年代",
        value: "-1990"
      },
      {
        name: "80年代",
        value: "-1980"
      },
      {
        name: "70年代",
        value: "-1970"
      },
      {
        name: "60年代",
        value: "-1960"
      },
      {
        name: "50年代",
        value: "-1950"
      },
      {
        name: "更早",
        value: "--1950"
      }
    ],
    curPage: 1,
    totalPage: 1,
    loading: false,
    isMoreData: false,
    requestData: {
      category_id: 0,
      area: '全部',
      year: 0
    }
  }),
  methods: {
    async getMovie(reset = false) {
      this.loading = true;
      let page = reset ? 1 : this.curPage + 1;
      if('search' in this.$route.query) {
        this.requestData.search = this.$route.query.search
      }
      let params = this.$util.queryParams(this.requestData)
      let requestData = {
        url: "/api/movies/search?include=cover_image,category&limit=100&page=" + page + "&" + params
      }

      let res = this.auth
        ? await this.$ajax.authRequest(requestData)
        : await this.$ajax.request(requestData);
      if (res.status === 200) {
        this.movies = reset ? res.data.data : this.movies.concat(res.data.data);
        this.movies.forEach((item, index) => {
          if (this.zoomId === index) this.movies[index] .zoom = true
          else this.movies[index] .zoom = false
        })
        this.curPage = res.data.meta.pagination.current_page;
        this.totalPage = res.data.meta.pagination.total_pages;
        this.$nextTick(() => {
          this.pullingDownUp();
        });
      }
    },
    zoom(index) {
      this.zoomId = index
      this.movies.forEach((item, i) => {
        if (i !== index) {
          item.zoom = false
          this.$set(this.movies, i, item)
        }
      })
      let movie = this.movies[index]
      movie.zoom = !movie.zoom
      this.$set(this.movies, index, movie)
      console.log(this.movies)
    },
    pullingDownUp() {
      this.loading = false;
      if (this.curPage < this.totalPage) this.isMoreData = true;
    },
    async scroll() {
      let scrollTop = document.querySelector(".md-app-container").scrollTop;
      let height = document.querySelector(".md-app-container").scrollHeight;
      let clientHeight = document.body.clientHeight;

      if (
        scrollTop + 200 + clientHeight >= height &&
        !this.loading &&
        this.isMoreData
      ) {
        await this.getMovie();
      }
    },
    async getCategories() {
      let res = await this.$ajax.request({ url: "/api/categories" });
      if (res.status === 200) {
        this.categories = res.data.data;
        this.areas = res.data.meta.areas;
      }
    },
    async reload(options) {
      let requestData = this.requestData
      Object.assign(requestData, options)
      this.requestData = requestData
      await this.getMovie(true)
    },
    isZoom(index) {
      return this.zoomId === index ? true : false
    },
    show(msg) {
      alert(msg)
    },
    showMsg(msg) {
      this.message = msg
      this.showMessage = true
    },
    async watch(id) {
      if (!this.auth) {
        this.showMsg('请登录')
        return
      }
      let res = await this.$ajax.updateWatchStatus(id, 'watching')
      console.log(res)
      if (res.status === 200) {
        this.showMsg('打卡成功！')
        let index
        this.movies.forEach((item, i) => {
          if (item.id === id) {
            index = i
          }
        })
        let movie = this.movies[index]
        movie.isWatch = res.data.meta.status
        movie.current_user_watch_status = res.data.meta.watch_status
        this.updateMovie(id, movie)
      }
    },
    async watched(id) {
      if (!this.auth) {
        this.showMsg('请登录')
        return
      }
      try{
        let res = await this.$ajax.updateWatchStatus(id, 'watched')
        if (res.status === 200) {
          this.showMsg('操作成功！')
          let index
          this.movies.forEach((item, i) => {
            if (item.id === id) {
              index = i
            }
          })
          let movie = this.movies[index]
          movie.isWatch = res.data.meta.status
          movie.current_user_watch_status = res.data.meta.watch_status
          this.updateMovie(id, movie)
        }
      } catch(error) {
        this.showMsg(error.response.data.message)
      }

      // console.log(res)
    },
    updateMovie(id, data) {
      this.movies.forEach((item, i) => {
        if (id === item.id) {
          this.$set(this.movies, i, data)
        }
      })
    }
  },
  mounted() {
    this.container = document.querySelector(".md-app-container");
    this.container.addEventListener("scroll", this.scroll, true);
  },
  created() {
    this.getMovie(true);
    this.getCategories();
  },
  destroyed() {
    this.container.removeEventListener("scroll", this.scroll, true);
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    '$route': 'getMovie'
  },
};
</script>
<style lang="scss" scoped>
.home {
  max-width: 1320px;
  margin: 0 auto;
  .movie-filters {
    padding: 4px;
  }
  .movie-top-progress {
    min-height: 5px;
  }
  .movie-list {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-left: -4px;
    margin-right: -4px;
    .movie-minbox {
      margin-top: 16px;
      display: flex;
      flex: row;
      .box-left{
        display: flex;
        flex-flow: column wrap;
        justify-content: space-between;
        max-width: 140px;
        overflow: hidden;
      }
      transition: all .2s linear .1s;
      .md-card-media img {
        width: 140px;
        min-width: 140px;
      }
      &.zoom {
        width: 280px;
        .md-list {
            .md-list-item {
              margin:0 -12px;
              .md-button {
                margin-left: 6px;
              }
            }
        }
      }
      .md-card-media {
        cursor: pointer;
      }
      .md-card-header {
        margin-bottom: 0;
        padding: 8px;
        .md-subhead {
          overflow: hidden;
          a {
            text-align: center;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: block;
            max-width: 124px;
            overflow: hidden;
            &:hover{
              text-decoration: none;
              color: var(--md-theme-default-accent-on-background, #ff5252);
            }
          }
        }
      }
    }
  }
  .movie-filter {
    margin: 5px auto;
    span {
      background-color: var(--md-theme-default-primary, #448aff);
      color: #fff;
      padding: 4px 8px;
      margin-right: 4px;
      line-height: 30px;
      cursor: pointer;
      &.active{
        background-color: var(--md-theme-default-accent-on-background, #ff5252);
      }
    }
  }
}
.md-card {
  width: 140px;
  margin: 4px;
  display: inline-block;
  vertical-align: top;
}
</style>
